// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// j [author] rhyme_lph
// r [email]  rhymelph@gmail.com
// p [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/product_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/object_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/adjust_product_number_form.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/products_services/adjust_inventory_list_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "adjustInventoryListPage")
class AdjustInventoryListPage extends StatefulWidget {
  final String status;

  const AdjustInventoryListPage({Key key, this.status}) : super(key: key);

  @override
  _AdjustInventoryListPageState createState() =>
      _AdjustInventoryListPageState();
}

class _AdjustInventoryListPageState extends State<AdjustInventoryListPage>
    with PagePresenter<AdjustInventoryListPage, AdjustInventoryListProvider> {
  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.adjust_inventory, actions: []);

  @override
  void initState() {
    provider.currentStatus = widget.status;
    super.initState();
  }

  @override
  Widget get buildWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                listBuilder<DateTime>(
                  selector: (_, __) => __.date,
                  builder:
                      (BuildContext context, DateTime value, Widget child) =>
                          ValueSelectForm(
                    title: S.current.date,
                    value: ObjectUtils.isNullDefaultFormat<DateTime>(
                        value,
                        null,
                        (data) => DateTimeUtils.formatGlobalDateTime(data)),
                    onTap: provider.onChangeIssueDate,
                  ),
                ),
                NormalFormWrapper(
                  child: listBuilder<
                      Tuple2<List<String>, List<OcrAttachmentEntity>>>(
                    selector: (_, __) => Tuple2(
                        List.from(__.files), List.from(__.attachments ?? [])),
                    builder: (BuildContext context,
                            Tuple2<List<String>, List<OcrAttachmentEntity>>
                                value,
                            Widget child) =>
                        AttachFileForm(
                      onAdd: provider.onAddAttachment,
                      files: value.item1,
                      onSelectFile: provider.onSelectFile,
                      attachments: value.item2,
                      onSelectAttachment: provider.onSelectAttachment,
                    ),
                  ),
                ),
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<Map<String, List<ProductEntity>>>(
                    selector: (_, __) =>
                        Map<String, List<ProductEntity>>.from(__.groupMap),
                    builder: (BuildContext context,
                            Map<String, List<ProductEntity>> value,
                            Widget child) =>
                        SmartRefresher(
                      controller: provider.refreshController,
                      onRefresh: provider.onRefresh,
                      onLoading: provider.onLoadMore,
                      enablePullUp: false,
                      child: CustomScrollView(
                        slivers: buildSearchWidget(),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  Widget _buildBottomBar() => Positioned(
        bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
        left: 0.0,
        right: 0.0,
        child: Center(
          child: NormalFloatTextButton(
            title: S.current.adjust,
            onTap: provider.onAdjust,
          ),
        ),
      );

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<ProductEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<ProductEntity> data, int i) {
    ProductEntity lastItemInList =
        provider.groupMap.entries.toList().map((e) => e.value).last.last;

    return listBuilder<Tuple2<ProductEntity, int>>(
        selector: (_, __) => Tuple2(data[i], __.numberMap[data[i].id]),
        builder: (BuildContext context, Tuple2<ProductEntity, int> value,
                Widget child) =>
            Column(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(35),
                    vertical: getDp(23),
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                        bottom:
                            BorderSide(color: aceGrayColor, width: getDp(0.5))),
                  ),
                  child: AdjustProductNumberForm(
                    title: value.item1.name,
                    content: S.current.stock_(value.item1.inventoryLeft),
                    initialNumber:
                        (value.item1.inventoryLeft ?? 0) + (value.item2 ?? 0),
                    otherValue: value.item2 == null
                        ? null
                        : (value.item2 - value.item1.inventoryLeft ?? 0),
                    onNumberCallback: (number) =>
                        provider.updateNumber(value.item1.id, number),
                    numberTitle: S.current.actual,
                  ),
                ),
                if (lastItemInList == data[i]) AppSpaces.h85(context),
              ],
            ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
